<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <div class="title-area">
      <div>
        <span>{{ deptName }}-{{ year }}年用能统计</span>
      </div>
      <div>
        <el-button type="warning" plain size="small" @click="handleExport">
          导出
        </el-button>
        <el-button size="small" @click="handlerGoback"> 返回 </el-button>
      </div>
    </div>
    <el-row>
      <el-col class="tag-area" :span="24">
        <el-tag
          v-for="(item, index) in tagArr"
          :key="index"
          size="medium"
          :type="item.type"
        >
          {{ item.label }}{{ item.value }}{{ item.unit }}
        </el-tag>
      </el-col>
    </el-row>
    <el-table
      ref="excelTable"
      :data="tableData.data"
      border
      :height="600"
      background
    >
      <el-table-column
        label="区域名称"
        prop="parkName"
        min-width="150"
        showOverflowTooltip
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="楼宇名称"
        prop="buildingName"
        min-width="100"
        showOverflowTooltip
        align="center"
      >
      </el-table-column>
      <el-table-column
        label="楼层名称"
        prop="floorName"
        min-width="100"
        align="center"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="房间类型"
        prop="roomTypeName"
        min-width="150"
        align="center"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="房间号"
        prop="name"
        min-width="100"
        align="center"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="房间名称"
        prop="nickname"
        align="center"
        min-width="150"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="房间面积（m²）"
        prop="roomArea"
        min-width="130"
        align="center"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="房间朝向"
        prop="direction"
        min-width="100"
        align="center"
        showOverflowTooltip
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.room_direction"
            :value="scope.row.direction"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="总人数"
        prop="userNum"
        min-width="100"
        align="center"
        showOverflowTooltip
      >
      </el-table-column>
      <el-table-column
        label="用能类型"
        prop="specialEnergyFlag"
        align="center"
        min-width="100"
        showOverflowTooltip
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.special_energy_consumption_type"
            :value="scope.row.specialEnergyFlag"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-for="n in 12"
        :key="n"
        prop="idx"
        :label="n + '月'"
        align="center"
      >
        <el-table-column
          label="人均电耗（kwh）"
          prop=""
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            {{
              (scope.row["month" + `${n}`]["totalElectric"] / scope.row.userNum)
                | filterTb
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="人均水耗（吨）"
          prop=""
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            {{
              (scope.row["month" + `${n}`]["totalWater"] /
                scope.row.userNum /
                1000)
                | filterTb
            }}
          </template>
        </el-table-column>
<!--        <el-table-column-->
<!--          label="人均碳排（kgCO2）"-->
<!--          prop=""-->
<!--          min-width="100"-->
<!--          show-overflow-tooltip-->
<!--          align="center"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            {{-->
<!--              (scope.row["month" + `${n}`]["totalCarbon"] / scope.row.userNum)-->
<!--                | filterTb-->
<!--            }}-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
          label="总电耗（kwh）"
          :prop="'month' + n + '.totalElectric'"
          min-width="85"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="总水耗（吨）"
          :prop="'month' + n + '.totalWater'"
          min-width="85"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row["month" + `${n}`]["totalWater"] / 1000 }}
          </template>
        </el-table-column>
        <el-table-column
          label="总碳排（kgCO2）"
          :prop="'month' + n + '.totalCarbon'"
          min-width="85"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="用电公摊（kwh）"
          :prop="'month' + n + '.sharedElectric'"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="用水公摊（吨）"
          :prop="'month' + n + '.sharedWater'"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row["month" + `${n}`]["sharedWater"] / 1000 }}
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="currentPage"
      :limit.sync="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      @pagination="handlerSearchDetail"
    />
  </lb-layout>
</template>

<script>
import { exportExcel } from "@/utils/xlsx";
import {
  getDeptStatisticsEnergyDetail,
  getDeptStatisticsEnergyDetailTotal,
} from "@/api/statistics/park.js";
import { deepClone, dealElectricity } from "@/utils/index";
export default {
  filters: {
    filterTb(val, format = true) {
      let text = val;
      if (!val || typeof value === "NaN") {
        text = "0";
      }
      return text;
    },
  },
  name: "deptStatisticsDetail",
  dicts: ["room_direction", "special_energy_consumption_type"],
  data() {
    return {
      tagArr: [
        {
          label: "用能面积：",
          value: 0,
          unit: "㎡",
          type: "success",
        },
        {
          label: "房间数量：",
          value: 0,
          unit: "间",
          type: "success",
        },
        {
          label: "用能人数：",
          value: 0,
          unit: "人",
          type: "success",
        },
        {
          label: "人均电耗：",
          value: 0,
          unit: "kwh",
          type: "danger",
        },
        {
          label: "人均水耗：",
          value: 0,
          unit: "吨",
          type: "danger",
        },
        // {
        //   label: "人均碳排：",
        //   value: 0,
        //   unit: "kgCO2",
        //   type: "danger",
        // },
        {
          label: "用电公摊：",
          value: 0,
          unit: "kwh",
          type: "danger",
        },
        {
          label: "用水公摊：",
          value: 0,
          unit: "吨",
          type: "danger",
        },
        {
          label: "实际费用：",
          value: 0,
          unit: "元",
          type: "warning",
        },
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      year: "",
      deptName: "",
      deptId: null,
      tableData: {
        column: [
          {
            prop: "parkName",
            label: "区域名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "buildingName",
            label: "楼宇名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "floorName",
            label: "楼层名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "roomTypeName",
            label: "房间类型",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "name",
            label: "房间号",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "nickname",
            label: "房间名称",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "roomArea",
            label: "房间面积",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "㎡";
              let value = scope.row.roomArea ?? 0;
              value = dealElectricity(value, 1, 2);
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "direction",
            label: "房间朝向",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.room_direction}
                    value={scope.row.direction}
                  />
                </div>
              );
            },
          },
          {
            prop: "userNum",
            label: "总人数",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "specialEnergyFlag",
            label: "用能类型",
            minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              return (
                <div>
                  <dict-tag
                    options={this.dict.type.special_energy_consumption_type}
                    value={scope.row.specialEnergyFlag}
                  />
                </div>
              );
            },
          },
          {
            prop: "",
            label: "人均电耗",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kwh";
              let totalElectric = scope?.row?.totalElectric ?? 0;
              let userNum = scope?.row?.userNum ?? 0;
              let value;
              if (userNum != 0) {
                value = dealElectricity(totalElectric / userNum, 1, 2);
              } else {
                value = "0.00";
              }
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "",
            label: "人均水耗",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "t";
              let totalWater = scope?.row?.totalWater ?? 0;
              let userNum = scope?.row?.userNum ?? 0;
              let value;
              if (userNum != 0) {
                value = dealElectricity(totalWater / userNum, 1000, 2);
              } else {
                value = "0.00";
              }
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          // {
          //   prop: "",
          //   label: "人均碳排",
          //   minWidth: 100,
          //   align: "center",
          //   showOverflowTooltip: true,
          //   render: (h, scope) => {
          //     let unit = "kgCO2";
          //     let totalCarbon = scope?.row?.totalCarbon ?? 0;
          //     let userNum = scope?.row?.userNum ?? 0;
          //     let value;
          //     if (userNum != 0) {
          //       value = dealElectricity(totalCarbon / userNum, 1, 2);
          //     } else {
          //       value = "0.00";
          //     }
          //     let a = value + unit;
          //     return <div>{a}</div>;
          //   },
          // },
          {
            prop: "",
            label: "总电耗",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kwh";
              let value = scope?.row?.totalElectric ?? 0;
              value = dealElectricity(value, 1, 2);
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "",
            label: "总水耗",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "t";
              let value = scope?.row?.totalWater ?? 0;
              value = dealElectricity(value, 1000, 2);
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "",
            label: "总碳排",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "kgCO2";
              let value = scope?.row?.totalCarbon ?? 0;
              value = dealElectricity(value, 1, 2);
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
          {
            prop: "",
            label: "实际费用",
            minWidth: 100,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let unit = "元";
              let value = scope?.row?.totalFee ?? 0;
              value = dealElectricity(value, 1, 2);
              let a = value + unit;
              return <div>{a}</div>;
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {},
  mounted() {
    this.handlerSearchDetail();
  },
  methods: {
    handleExport() {
      if (this.tableData.data.length <= 0) {
        this.$message.warning("无内容导出,请确认!");
        return false;
      }
      let fileName = this.deptName + "-" + this.year + "年用能统计";
      let cols = [{ wpx: 240 }];
      exportExcel(this.$refs.excelTable, fileName, cols);
    },
    requestTotal(data) {
      let that = this;
      let query = {
        ...data,
      };
      getDeptStatisticsEnergyDetailTotal(query)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let result = res?.data ?? {};
          this.tagArr[0].value = result?.totalArea ?? 0;
          this.tagArr[1].value = result?.roomNum ?? 0;
          let userNum = result?.userNum ?? 0;
          this.tagArr[2].value = result?.userNum ?? 0;
          let totalElectric = result?.totalElectric ?? 0;
          let totalWater = result?.totalWater ?? 0;
          let totalCarbon = result?.totalCarbon ?? 0;
          let ele, water, car;
          if (userNum != 0) {
            ele = dealElectricity(totalElectric / userNum, 1, 2);
            water = dealElectricity(totalWater / userNum, 1000, 2);
            car = dealElectricity(totalCarbon / userNum, 1, 2);
          } else {
            ele = "0.00";
            water = "0.00";
            car = "0.00";
          }
          this.tagArr[3].value = ele;
          this.tagArr[4].value = water;
          this.tagArr[5].value = car;
          let sharedElectric = result?.sharedElectric ?? 0;
          let sharedWater = result?.sharedWater ?? 0;
          this.tagArr[6].value = dealElectricity(sharedElectric, 1, 2);
          this.tagArr[7].value = dealElectricity(sharedWater, 1000, 2);
          let totalFee = result?.totalFee ?? 0;
          this.tagArr[8].value = dealElectricity(totalFee, 1, 2);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      // query.pageNum = that.currentPage;
      // query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await getDeptStatisticsEnergyDetail(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      // console.log(this.$route.query, "路由参数");
      let query = this.$route.query;
      this.deptId = query.deptId;
      this.year = query.year;
      this.deptName = query.deptName;
      const data = {
        deptId: this.deptId,
        year: this.year,
      };
      this.initData(data);
      this.requestTotal(data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handlerGoback() {
      let pathRouter = this.$route.meta.activeMenu; // 激活的菜单也是返回的菜单
      let query = {};
      this.$router.push({
        path: pathRouter,
        query: query,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.title-area {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  span {
    font-size: 24px;
    font-weight: 400;
  }
}
.tag-area {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .el-tag {
    margin-right: 10px;
  }
}
</style>
